package cn.jinbyte.starter.message.aspect;


import cn.jinbyte.starter.message.model.NoticeLog;
import cn.jinbyte.starter.message.service.NoticeLogService;
import cn.jinbyte.starter.message.model.NoticeType;
import cn.jinbyte.starter.message.annotation.EmailNoticeLog;
import cn.jinbyte.starter.message.model.EmailNoticeDTO;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 邮件通知日志切面
 */
@Aspect
public class EmailLogAspect {

    private final NoticeLogService noticeLogService;

    public EmailLogAspect(NoticeLogService noticeLogService) {
        this.noticeLogService = noticeLogService;
    }

    /**
     * {@link EmailNoticeLog}
     */
    @Pointcut("@annotation(cn.jinbyte.starter.message.annotation.EmailNoticeLog)")
    public void pointcut() {
    }

    @Around(value = "pointcut() && args(notice)", argNames = "joinPoint, notice")
    public Object noticeLog(ProceedingJoinPoint joinPoint, EmailNoticeDTO notice) throws Throwable {
        return emailNoticeLog(joinPoint, notice);
    }

    private Object emailNoticeLog(ProceedingJoinPoint joinPoint, EmailNoticeDTO notice) throws Throwable {
        NoticeLog log = new NoticeLog();
        log.setNoticeType(NoticeType.EMAIL.name());
        log.setNoticeTarget(notice.getTo());
        log.setNoticeContent(notice.getContent());
        log.setCreateBy(notice.getCreateBy());
        log.setStatus("成功");
        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            log.setStatus("失败");
            log.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            throw e;
        } finally {
            noticeLogService.saveNoticeLog(log);
        }
    }
}

